package com.engineering.elink.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.ws.rs.DefaultValue;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.engineering.elink.co.BaseCo;
import com.engineering.elink.co.FileCo;
import com.engineering.elink.common.Constant;
import com.engineering.elink.common.ErrorType;
import com.engineering.elink.domain.File;
import com.engineering.elink.service.FileService;
import com.engineering.elink.util.JSONUtil;
import common.model.ResponseObject;

/**
 * 文件
 * @author hxjxiaojun
 * @time   2016年8月30日
 */
@Controller
@CrossOrigin
@RequestMapping("/api/file")
@Api(value = "资料库接口")
public class FileController {
	@Autowired
	private FileService fileService;
	
	/**
	 * 获取资料库列表
	 * @param co
	 * @return
	 */
	@RequestMapping(value="/getList",method = RequestMethod.GET)
	@ApiOperation(value = "资料库列表")
	@ResponseBody
	public Map<String, Object>getList(@ModelAttribute @Valid FileCo co){
		return fileService.getFilesList(co);
	}
	
	/**
	 * 统计个人中心-首页--职业规划里的信息
	 * @param hoerId
	 * @return
	 */
	@RequestMapping(value="/getPlanList",method = RequestMethod.GET)
	@ApiOperation(value = "个人中心-首页--职业规划",notes="统计个人中心-首页--职业规划里的信息")
	@ResponseBody
	public Map<String, Object>getPlanList(
			@ApiParam(value="职业id",required=true)@RequestParam(value="hierId",required=true)int hierId,
			@ApiParam(value="等级，1--入门 ，2--进阶。默认1",required=true,defaultValue="1")
			@RequestParam(value="gradeId",required=true,defaultValue="1")int gradeId){
		return fileService.getPlanList(hierId,gradeId);
	}
	
	/**
	 * 统计个人中心-首页--工程资料库
	 * @param hoerId
	 * @return
	 */
	@RequestMapping(value="/getDatabaseList",method = RequestMethod.GET)
	@ApiOperation(value = "统计个人中心-首页--工程资料库",notes="统计个人中心-首页--工程资料库")
	@ResponseBody
	public Map<String, Object>getFileList(@ApiParam(value="国内资料的二级分类id",required=true)
	@RequestParam(value="scId",required=true)int scId){
		return fileService.getDatabaseList(scId);
	}
	
	/**
	 * 项目首页--职业考证体系
	 * @return
	 */
	@RequestMapping(value="/getFileSystem",method = RequestMethod.GET)
	@ApiOperation(value = "项目首页--职业考证体系",notes="项目首页--职业考证体系")
	@ResponseBody
	public Map<String, Object>getFileSystem(@ApiParam(value="显示条数,默认为6条",defaultValue="6") 
	@RequestParam("count") @DefaultValue("6")int count){
		return fileService.getFileSystem(count);
	}
	
	/**
	 * 项目首页--职业考证体系--资料
	 * @return
	 */
	@RequestMapping(value="/getFile",method = RequestMethod.GET)
	@ApiOperation(value = "项目首页--职业考证体系",notes="项目首页--职业考证体系")
	@ResponseBody
	public Map<String, Object>getFile(@ApiParam(value="显示条数,默认为6条",defaultValue="6") 
	@RequestParam("count") @DefaultValue("6")int count){
		return fileService.getFile(count);
	}
	
	/**
	 * 相关热门资料
	 * @param fileId
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getHotFile",method = RequestMethod.GET)
	@ApiOperation(value = "相关热门资料",httpMethod="GET",notes="建筑类别体系--相关热门资料")
	@ResponseBody
	public Map<String, Object>getHotFile(
			@ApiParam(value="二级分类id",required=false,defaultValue="0")@RequestParam(value="scId",required=false,defaultValue="0")int  scId,
			@ApiParam(value="三级分类id",required=false,defaultValue="0")@RequestParam(value="dcId",required=false,defaultValue="0")int  dcId,
			@ApiParam(value="显示条数，默认为8条",required=true,defaultValue="8")
			@RequestParam(value = "count",required=true,defaultValue="8")int count){
		return fileService.getHotFile(scId,dcId,count);
	}
	
	/**
	 * 添加文件
	 * @param file
	 * @param dcIds
	 * @return
	 */
	
	@RequestMapping(value="/add",method = RequestMethod.POST)
	@ApiOperation(value = "添加文件")
	@ResponseBody
	public Map<String, Object>add(@ModelAttribute @Valid File file,
			@ApiParam(value="详情分类,比如'1,2,3'",required = true)@RequestParam("dcIds")String dcIds,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		file.setUserId(userId);
		return fileService.add(file,dcIds);
	}
	
	/**
	 * 	修改文件 	
	 * @param file
	 * @param dcIds
	 * @return
	 */
	@RequestMapping(value="/update",method = RequestMethod.POST)
	@ApiOperation(value = "修改文件")
	@ResponseBody
	public Map<String, Object>update(@ModelAttribute @Valid File file,
			@ApiParam(value="详情分类,比如'1,2,3'",required = true)@RequestParam("dcIds")String dcIds,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>)request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		file.setUserId(userId);
		return fileService.update(file,dcIds);
	}
	
	
	/**
	 * 获取资料详情
	 * @param fileId
	 * @return
	 */
	@RequestMapping(value="/get",method = RequestMethod.GET)
	@ApiOperation(value = "资料详情")
	@ResponseBody
	public Map<String, Object>get(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "fileId",required=true)String fileId,HttpServletRequest request){
		String userId =null;
		try {
			@SuppressWarnings("unchecked")
			Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
			userId =  userInfo.get("userId").toString();
		} catch (Exception e) {
		}
		return fileService.get(fileId,userId);
	}

	/**
	 * 获取共享资料
	 * @param fileId
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getShare",method = RequestMethod.GET)
	@ApiOperation(value = "资料共享资料")
	@ResponseBody
	public Map<String, Object>getShare(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "fileId",required=true)String fileId){
		return fileService.getShare(fileId);
	}
	
	
	/**
	 * 预览文件
	 * @param fileId
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getPreviewPngOfFile",method = RequestMethod.GET)
	@ApiOperation(value = "预览文件")
	@ResponseBody
	public Map<String,Object>getPreviewPngOfFile(@ApiParam(value="资料id",required=true)
	@RequestParam(value = "fileId",required=true)String fileId,
	@ApiParam(value="文件类型,1--资料，2--论文",required=true,defaultValue="1")
	@RequestParam(value = "type",required=true,defaultValue="1")int type,
	HttpServletRequest request){
		String userId =null;
		try {
			@SuppressWarnings("unchecked")
			Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
			userId =  userInfo.get("userId").toString();
		} catch (Exception e) {
		}
		return fileService.getPreviewPngOfFile(fileId,userId,type);
	}
	
	/**
	 * 获取下载排行
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getDownLoadRank",method = RequestMethod.GET)
	@ApiOperation(value = "下载排行")
	@ResponseBody
	public Map<String, Object>getDownLoadRank(
			@ApiParam(value="显示条数,默认为10条",defaultValue="10") @RequestParam("count") @DefaultValue("10")int count,
			@ApiParam(value="类型,0--工程资料，1--职业考证体系",defaultValue="0")
			@RequestParam(value="mold",required=false) @DefaultValue("0")int mold){
		return fileService.getDownLoadRank(count,mold);
	}
	
	/**
	 * 获取相关推荐
	 * @param fileId
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getRelevant",method = RequestMethod.GET)
	@ApiOperation(value = "相关推荐")
	@ResponseBody
	public Map<String, Object>getRelevant(
			@ApiParam(value="资料id",required=true)@RequestParam("fileId")String fileId,
			@ApiParam(value="显示条数",required=true,defaultValue="6")
			@RequestParam(value = "count",required=true,defaultValue="6")int count){
		return fileService.getRelevant(fileId,count);
	}
	
	/**
	 * 获取资讯分类
	 * @param fileId
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getRelevantType",method = RequestMethod.GET)
	@ApiOperation(value = "获取资讯分类", response = ResponseObject.class)
	@ResponseBody
	public Map<String, Object>getRelevantType(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "fileId",required=true)String fileId,
			@ApiParam(value="获取资讯分类,默认为9条",required=false,defaultValue="9")
			@RequestParam(value = "count",required=false,defaultValue="9")int count){
		return fileService.getRelevantType(fileId,count);
	}
	
	/**
	 * 猜你喜欢
	 * @param fileId
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getLike",method = RequestMethod.GET)
	@ApiOperation(value = "猜你喜欢", response = ResponseObject.class)
	@ResponseBody
	public Map<String, Object>getLike(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "fileId",required=true)String fileId,
			@ApiParam(value="显示条数,默认为6条",required=true,defaultValue="6")
			@RequestParam(value = "count",required=true,defaultValue="6")int count){
		return fileService.getLike(fileId,count);
	}
	
	/**
	 * 获取热搜词
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getKeyWord",method = RequestMethod.GET)
	@ApiOperation(value = "获取热搜词", response = ResponseObject.class)
	@ResponseBody
	public Map<String, Object>getKeyWord(
			@ApiParam(value="显示条数,默认为6条",required=false,defaultValue="6")
			@RequestParam(value = "count",required=false,defaultValue="6")int count){
		return fileService.getKeyWord(count);
	}
	
	
	/**
	 * 获取工程资料精选
	 * @param count
	 * @return
	 */
	@RequestMapping(value="/getFileBest",method = RequestMethod.GET)
	@ApiOperation(value = "项目首页--工程资料精选", response = ResponseObject.class,notes="项目首页--获取工程资料精选")
	@ResponseBody
	public Map<String, Object>getFileBest(@ApiParam(value="获取工程资料精选,默认为5条",required=false,defaultValue="5")
	@RequestParam(value = "count",required=false,defaultValue="5")int count){
		return fileService.getFileBest(count);
	}
	
	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	@SuppressWarnings({ "deprecation", "unused" })
	@RequestMapping(value = "upload", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
	@ApiOperation(value = "上传文件", response = ResponseObject.class)
	@ResponseBody
	public Map<String, Object> uploadFile(
			@ApiParam(value="上传文件",required=true)
			@RequestParam("file") MultipartFile file) {		
		
		String fileName = file.getOriginalFilename();
		String suffix = "";
		String newFileName = "";
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			suffix = fileName.substring(index);
		}
//		if(!isExcept(suffix)){
//			return JSONUtil.getJSON(ErrorType.FILE_TYPE_ERROR);
//		}
		Date d = new Date();
		int year = d.getYear()+1900;
		int month = d.getMonth()+1;
		int day = d.getDate();
		
		String basePath = year+month+day +"/"+d.getTime();
	     newFileName = "file/" +basePath + suffix;
		 String path = Constant.WEB_SERVER_PATH+"/" + newFileName;
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new java.io.File(path));
			String url =Constant.WEB_SERVER_URL+"/" + newFileName;//下载路径
			//预览路径
			String previewName = basePath+ ".pdf";
			
			String previewPath = Constant.WEB_SERVER_PATH+"/" + "pdf/"+ previewName;
//			OpenOffice2PDF office2pdf = new OpenOffice2PDF();
			
//			office2pdf.openOffice2Pdf(path,previewName);
//			FileUtils.copyFile(new java.io.File(previewName), new java.io.File(previewPath));
			
			String previewUrl = Constant.WEB_SERVER_URL+"/" + "pdf/"+ previewName ;//预览路径
			
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("downloadUrl", url);
	        map.put("previewUrl", previewUrl);
	        
			return JSONUtil.getJSON(ErrorType.SUCCESS, map);

		} catch (IOException e) {
			return JSONUtil.getJSON(ErrorType.HANDLE_FILE_ERROR);
		}
	}
	
	/**
	 * 下载文件
	 * @param fileId
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "download", method = RequestMethod.GET)
	@ApiOperation(value = "下载文件", response = ResponseObject.class)
	@ResponseBody
	public Map<String, Object> downloadFile(
			@ApiParam(value="资料id",required=true)@RequestParam(value = "fileId",required=true)String fileId,
			HttpServletResponse response,HttpServletRequest request
			) throws Exception {
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>)request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		return  fileService.download(response,request,userId,fileId);
	}
	
	/**
	 * 分页获取我上传的文件
	 * @param co
	 * @return
	 */
	@RequestMapping(value="/myUploadFile",method = RequestMethod.GET)
	@ApiOperation(value="分页获取我上传的文件")
	@ResponseBody
	public Map<String, Object> myUploadFile(@ModelAttribute @Valid BaseCo co,
			@ApiParam(value="搜索关键词",required=false,defaultValue="")
	@RequestParam(value="keyWord",required=false,defaultValue="")String keyWord,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		return fileService.getMyUploadFile(co,userId,keyWord);
	}
	
	/**
	 * 分页获取TA上传的资料
	 * @param co
	 * @param keyWord
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/uploadFileByUserId",method = RequestMethod.GET)
	@ApiOperation(value="分页获取TA上传的文件",httpMethod="GET",notes="分页获取TA上传的资料")
	@ResponseBody
	public Map<String, Object> uploadFileByUserId(
			@ModelAttribute @Valid BaseCo co,@ApiParam(value="搜索关键词",required=false,defaultValue="")
			@RequestParam(value="keyWord",required=false,defaultValue="")String keyWord,@ApiParam(value="用户ID",required=true)
			@RequestParam(value="userId",required=true)String userId){
		return fileService.getMyUploadFile(co,userId,keyWord);
	}
	/**
	 * 分页获取我下载的文件
	 * @param co
	 * @return
	 */
	@RequestMapping(value="/myDownLoadFile",method = RequestMethod.GET)
	@ApiOperation(value="分页获取我下载的文件")
	@ResponseBody
	public Map<String, Object> myDownLoadFile(@ModelAttribute @Valid BaseCo co,
			@ApiParam(value="搜索关键词",required=false,defaultValue="")
	@RequestParam(value="keyWord",required=false,defaultValue="")String keyWord,HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String,Object> userInfo  = (Map<String, Object>) request.getAttribute("userInfo");
		String userId =  userInfo.get("userId").toString();
		return fileService.getMyDownLoadFile(co,userId,keyWord);
	}	
	/**
	 * 校验文件的格式
	 * @param url
	 * @return
	 */
	public 	boolean isExcept(String url){
		String[] excepts={".docx",".doc",".ppt",".xls"};
		boolean flag=false;
		for(String e:excepts){
			if(url!=null&&url.endsWith(e)){
				flag=true;
				break;
			}
		}
		return flag;
	}
	
	@RequestMapping(value="/getTest",method = RequestMethod.GET)
	@ApiOperation(value = "资料转码测试")
	@ResponseBody
	public Map<String, Object>getTest(@ApiParam(value="路径",required=false,defaultValue="")
	@RequestParam(value="lujing",required=false,defaultValue="")String lujing){
		return fileService.getTest(lujing);
	}
	
	@RequestMapping(value="/getTest2",method = RequestMethod.GET)
	@ApiOperation(value = "论文转码测试")
	@ResponseBody
	public Map<String, Object>getTest2(@ApiParam(value="路径",required=false,defaultValue="")
	@RequestParam(value="lujing",required=false,defaultValue="")String lujing){
		return fileService.getTest2(lujing);
	}
}
